<?php

namespace app\adminapi\controller\v1\office;

use app\adminapi\controller\AuthController;
use app\api\controller\v1\Face;
use app\dao\office\OfficeStudentDao;
use app\exceptions\AdminException;
use app\model\office\OfficeUser;
use app\services\office\OfficeStudentService;
use hg\apidoc\annotation\Field;
use OSS\Core\OssException;
use OSS\OssClient;
use think\db\Where;
use think\facade\App;
use think\facade\Filesystem;
use think\facade\Request;
use function MongoDB\BSON\toJSON;

class OfficeStudent extends AuthController
{
    public function __construct(App $app, OfficeStudentService $service)
    {
        parent::__construct($app);
        $this->services = $service;
    }


    public function index()
    {
        $where = $this->request->postMore([
            ['page', 1],
            ['pageSize', 20],
            ['website_id', $this->website],
        ]);
        return app()->make('json')->successful($this->services->index($where));
    }

    public function create()
    {
        $where = $this->request->postMore([
            ['website_id', $this->website],
            ['major_id', ''],
            ['heard', ''],
            ['name', ''],
            ['sex', ''],
            ['adress', ''],
            ['postal_code', ''],
            ['idcard', ''],
            ['phone', ''],
            ['exam_number', ''],
            ['pwd', ''],
            ['enter_batch', ''],
            ['enter_type', ''],
            ['student_number', ''],
            ['birthday', ''],
            ['political', ''],
            ['graduated_school', '']

        ]);
        return app()->make('json')->successful($this->services->create($where));
    }

    public function update()
    {
        $where = $this->request->postMore([
            ['id', ''],
            ['major_id', ''],
            ['heard', ''],
            ['name', ''],
            ['sex', ''],
            ['adress', ''],
            ['postal_code', ''],
            ['idcard', ''],
            ['phone', ''],
            ['exam_number', ''],
            ['pwd', ''],
            ['enter_batch', ''],
            ['enter_type', ''],
            ['student_number', ''],
            ['birthday', ''],
            ['political', ''],
            ['graduated_school', '']
        ]);
        return app()->make('json')->successful($this->services->update($where));
    }

    public function delete()
    {
        $where = $this->request->postMore([
            ['id', ''],
        ]);
        return app()->make('json')->successful($this->services->delete($where));
    }

    public function search()
    {
        $where = $this->request->postMore([
            ['website_id', $this->website],
            ['major_id', ''],
            ['name', ''],
            ['sex', ''],
            ['idcard', ''],
            ['phone', ''],
            ['exam_number', ''],
            ['enter_batch', ''],
            ['enter_type', ''],
            ['student_number', ''],
            ['page', 1],
            ['pageSize', 20],
        ]);
        return app()->make('json')->successful($this->services->search($where));
    }

    public function selectAllSearchToExcel()
    {
        $where = $this->request->postMore([
            ['website_id', $this->website],
            ['major_id', ''],
            ['name', ''],
            ['sex', ''],
            ['idcard', ''],
            ['phone', ''],
            ['exam_number', ''],
            ['enter_batch', ''],
            ['enter_type', ''],
            ['student_number', ''],
        ]);
        return app()->make('json')->successful($this->services->selectAllSearchToExcel($where));
    }

    public function getUserList()
    {
        $where = $this->request->postMore([
            ['website_id', $this->website],
            ['page', 1],
            ['pageSize', 20],
            ['name', ''],
        ]);
        return app()->make('json')->successful($this->services->getUserList($where));
    }

    public function getIdsFormUser()
    {
        $where = $this->request->postMore([
            ['ids', ''],
            ['major_id', ''],
            ['name', ''],
            ['sex', ''],
            ['idcard', ''],
            ['phone', ''],
            ['exam_number', ''],
            ['enter_batch', ''],
            ['enter_type', ''],
            ['student_number', ''],
            ['page', 1],
            ['pageSize', 20],
        ]);
        if (empty($where['ids'])) throw new AdminException('缺少必要参数');
        return app()->make('json')->successful($this->services->getIdsFormUser($where));
    }

    public function excelOutFromIds()
    {
        $where = $this->request->postMore([
            ['ids', ''],
        ]);
        if (!$where['ids']) throw new AdminException('缺少必要参数');
        return app()->make('json')->successful($this->services->excelOutFromIds($where));
    }

    public function downloadTemplate()
    {
        $file = $_SERVER['DOCUMENT_ROOT'] . '/excelTemplate/' . '学生信息导入模板.xls';
        return download($file, '学生信息导入模板.xls');
    }

    /**
     * 批量导入头像
     * @return void
     */
    public function EnterHeardImageForUser()
    {
        $files = $_FILES['file'];
        $name = $files['name'];
        $format = strrchr($name, '.');//截取文件后缀名如 (.jpg)
        $identity = explode('.', $name)[0];

        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        $accessKeyId = Filesystem::getDiskConfig('aliyun', 'accessId');
        $accessKeySecret = Filesystem::getDiskConfig('aliyun', 'accessSecret');
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        $endpoint = Filesystem::getDiskConfig('aliyun', 'endpoint');
        // 设置存储空间名称。
        $bucket = Filesystem::getDiskConfig('aliyun', 'bucket');
        $path = 'free/' . date('Y-m-d', time()) . '/';
        $object = $path . sha1(date('YmdHis', time()) . uniqid()) . $format;;
        $filePath = $files['tmp_name'];
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $result = $ossClient->uploadFile($bucket, $object, $filePath);
            if (!$result) {
                throw new AdminException("文件上传失败！");
            } else {
                $data['src'] = $result['info']['url'];
                $user = (new OfficeUser())->where('idcard', $identity)->find();
                $user->heard = $data['src'];
                $user->save();
                if (!$user) {
                    throw new AdminException("更新用户头像失败！");
                }
                return app()->make('json')->successful($user);
            }
        } catch (OssException $e) {
            throw new AdminException($e->getMessage());
        }

    }

    /**
     * 同步人脸识别库
     * @return void
     */
    public function synchronousFace()
    {

        $where = $this->request->postMore([
            ['userList', ''],
        ]);
        if (is_null($where['userList'])) throw new AdminException('缺少必要参数！');
        $face = app() -> make(Face::class);
        foreach ($where['userList'] as $data) {
            $face->addFaceUser($data);
        }
        return app()->make('json')->successful($where['userList']);

    }
}